var map = null;
var cityNow = '北京';
var defaultLevel = 11;

var $ = SJS['$'];
var addLoadEvent = SJS['addLoadEvent'];
var hasClassName = SJS['hasClassName'];
var addClass = SJS['addClass'];
var removeClass = SJS['removeClass'];
var show = SJS['show'];
var hide = SJS['hide'];
var getElementsByClassName = SJS['getElementsByClassName'];
var log = SJS['log'];

function showArea() {
	$('showArea').onclick = function () {
		if ($('area').style.display == 'block') {
			hide($('area'));
			this.innerHTML = '[切换地区]';
		}
		else {
			show($('area'));
			this.innerHTML = '[隐藏]';
		}
		return false;
	}
	/**
	* @param 父级区域的节点
	* @param 子级区域容器的ID
	* @param 需要处理的子级区域的className
	*/
	function showSubArea(parentAreaObj, subAreaDiv, subAreaClass) {
		parentAreaObj.onclick = function () {
			hide($('districts'));
			if (!hasClassName(parentAreaObj.className, 'clicked'))//以前没有点击过
			{
				addClass(parentAreaObj, "clicked");
			}
			var subArea = $(subAreaDiv);
			show(subArea);

			var parentId = parentAreaObj.getAttribute('id');
			getElementsByClassName(subArea, 'span', subAreaClass).each(function () {
				var subAreaNow = this;
				//alert(subAreaNow.getAttribute('id'));
				if (hasClassName(subAreaNow.className, parentId)) {
					show(subAreaNow, 'inline');
				}
				else {
					hide(subAreaNow);
				}
			});
		}
	}
	if (isMobile) {
		getElementsByClassName($('toolbar'), 'span,img,div,input', 'tool').each(function () {
			$('toolbar').removeChild(this);
		});
		///$('searchTip').style.fontSize = '12px';
	}

	getElementsByClassName($('provinces'), 'span', 'province').each(function () {//省的响应事件				
		showSubArea(this, 'citys', 'city');
	});
	getElementsByClassName($('citys'), 'span', 'city').each(function () {//市的响应事件
		showSubArea(this, 'districts', 'district');
	});
	getElementsByClassName($('districts'), 'span', 'district').each(function () {//县的响应事件
		var obj = this;
		obj.onclick = function () {
			var longitude = obj.getAttribute('long');
			var latitude = obj.getAttribute('lat');
			map.centerAndZoom(new BMap.Point(longitude, latitude), 17);
			if (!hasClassName(obj.className, 'clicked')) {
				addClass(obj, 'clicked');
			}
			$('cityNow').innerHTML = obj.innerHTML;
		}
	});

	show($('toolbar'));
	log.info('[showArea] end');
}

function initMap(longitudeNow, latitudeNow) {

	map = new BMap.Map("container");//地图所在容器
	longitudeNow = longitudeNow || longitude;
	latitudeNow = latitudeNow || latitude;
	var point = new BMap.Point(116.404, 39.915);  // 创建点坐标  
	map.centerAndZoom(point, defaultLevel);  //城市名,缩放等级11
	var opts = {
		//type: BMAP_NAVIGATION_CONTROL_SMALL,//使用小图标（默认使用大图标）
		anchor: BMAP_ANCHOR_TOP_RIGHT,//靠右显示（默认靠左显示）
		offset: new BMap.Size(10, 10)
	};
	map.addControl(new BMap.NavigationControl(opts));//添加缩放控件
	map.addControl(new BMap.ScaleControl());// 添加比例尺控件
	//map.addControl(new BMap.OverviewMapControl());              //添加缩略地图控件	
	log.info('map added');

	addMapFunction();	//添加地图监听函数
}
function addMapFunction() {
	if (!isMobile) {
		log.info('autocomplete');

		var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{
				"input": "searchArea"
				, "location": map
			});

		ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
			var str = "";
			var _value = e.fromitem.value;
			var value = "";
			if (e.fromitem.index > -1) {
				value = _value.province + _value.city + _value.district + _value.street + _value.business;
			}

			value = "";
			if (e.toitem.index > -1) {
				_value = e.toitem.value;
				value = _value.province + _value.city + _value.district + _value.street + _value.business;
			}
		});

		var myValue;
		ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
			var _value = e.item.value;
			myValue = _value.province + _value.city + _value.district + _value.street + _value.business;
			setPlace();
		});

		function setPlace() {
			map.clearOverlays();    //清除地图上所有覆盖物
			function myFun() {
				var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
				map.centerAndZoom(pp, 18);
				map.addOverlay(new BMap.Marker(pp));    //添加标注
			}
			var local = new BMap.LocalSearch(map, { //智能搜索
				onSearchComplete: myFun
			});
			local.search(myValue);
		}
	}
	$('search').onclick = function () {
		var local = new BMap.LocalSearch(map, {//local保存了当前地点对象
			renderOptions: {
				map: map
				//autoViewport: true
				//selectFirstResult: false
			}
		});
		if (!isMobile) {
			var place = $('searchArea').value;
			//alert(place);
			local.search(place);
			//local.searchInBounds(place, map.getBounds());
			log.info('search');
		}
		else {
			var place = prompt('请输入查询地点')
			if (place) {
				local.search(place);
				//local.searchInBounds(place, map.getBounds());			
			}
		}
	}

	if (!isMobile) {
		var myDis = new BMapLib.DistanceTool(map);
		var distanceMeasure = false;
		var rectangleShow = false;
		/**
		* 点击地图右上方的[开启]按钮,然后点击地图(不要在按钮上点),能看到变化,然后在地图上双击或点击[关闭]按钮,地图又发生了变代。
		*/
		var myDrag = new BMapLib.RectangleZoom(map, { followText: "拖拽鼠标进行操作" });
		$('distance').onclick = function () {//测距
			log.info('[distance] begin');
			if (!distanceMeasure) {
				myDis.open();
				this.setAttribute('src', 'images/btn_radio_on.png');
				distanceMeasure = true;
			}
			else {
				myDis.close();
				this.setAttribute('src', 'images/btn_radio_off.png');
				distanceMeasure = false;
			}
			log.info('[distance] end');
		}
		$('rectangle').onclick = function () {//画矩形
			if (!rectangleShow) {
				myDrag.open();
				this.setAttribute('src', 'images/btn_radio_on.png');
				rectangleShow = true;
			}
			else {
				myDrag.close();
				this.setAttribute('src', 'images/btn_radio_off.png');
				rectangleShow = false;
			}
		}
	}
}
addLoadEvent(showArea);	
